package com.zxy.leetcode._00000_00099._00080_00089;

import com.zxy.leetcode.common.ListNode;
import com.zxy.leetcode.common.ListNodeHelper;

/**
 * https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/
 *
 * 删除排序链表中的重复元素
 * 给定一个排序链表，删除所有重复的元素，使得每个元素只出现一次。
 */
public class Test00083 {

    public static void main(String[] args) {
        Test00083 test = new Test00083();
        int[] nums = {1, 1, 2, 2, 3, 3, 3, 3};
        ListNode head = ListNodeHelper.build(nums);
        head = test.deleteDuplicates(head);
        ListNodeHelper.print(head);
    }

    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        int pre = head.val;
        ListNode preNode = head;
        ListNode p = head.next;
        while (p != null) {
            if (p.val == pre) {
                if (p.next == null) {
                    preNode.next = null;
                }else {
                    preNode.next = p.next;
                }
            }else {
                pre = p.val;
                preNode = p;
            }
            p = p.next;
        }

        return head;
    }

    /**
     * 官网解法
     */
    public ListNode deleteDuplicates2(ListNode head) {
        ListNode current = head;
        while (current != null && current.next != null) {
            if (current.next.val == current.val) {
                current.next = current.next.next;
            } else {
                current = current.next;
            }
        }
        return head;
    }
}
